<?php

namespace App\Http\Controllers\home;

use Illuminate\Http\Request;
use DB;
use App\Http\Requests;
use App\Http\Controllers\Controller;

class WriteController extends Controller
{
    /**
     * 我的文章
     *
     * @return data
     */
    public function getWdwz()
    {
        //开启session
        session_start();
        //获取用户id
        $id = $_SESSION['id'];
        //查询所有文章
        $data = DB::table('article')
            ->Join('topic','topic.id','=','article.tid')
            ->select('article.*','topic.title as ttitle','topic.pic')
            ->orderBy('time','desc')
            ->where('article.uid',$id)
            ->where('astatus','=','0')
            ->get();
        return view('/home/write/wdwz',['data'=>$data]);
    }

    /**
     * 写文章页面
     *
     * @return view
     */
    public function getIndex()
    {
        return view('/home.write.index');
    }

    /**
     * ajax搜索话题
     *
     * @return data
     */
    public function getSousuo(Request $request)
    {
        //查询话题
        $data = DB::table('topic')
            ->where('title','like','%'.$request->input('topic').'%')
            ->get();

        //分配模板
        return $data;
    }

    /**
     * 执行上传
     *
     * @return res
     */
    public function postAdd(Request $request)
    {
        session_start();
        $id = $_SESSION['id'];

        //获取文章内容
        $data = $request->except(['_token','topic']);
        
        //获取时间
        $date = time();
        //执行添加文章操作
        $res = DB::table('article')
            ->insert([
                ['tid'=>$data['tid'],'title'=>$data['title'],'content'=>$data['content'],'time'=>$date,'uid'=>$id]
                ]);
        //判断是否发表成功
        if($res){
           echo "<script>alert('发布成功');window.location.href='{$_SERVER['HTTP_REFERER']}'</script>";
         }else{
            echo "<script>alert('发布失败!');window.location.href='{$_SERVER['HTTP_REFERER']}'</script>";
         }
    }

    /**
     * 执行点赞操作
     *
     * @return res
     */
    public function getDianzan(Request $request)
    {
        //开启session
        session_start();
        //获取用户id
        $id = $_SESSION['id'];
        //获取当前时间戳
        $time = time();
        //获取要点赞的文章id
        $wzid = $request->input('wzid');
        //查询是否已经点赞
        $rees = DB::table('guanxiwz')->where('wzid',$wzid)->where('uuuid',$id)->get();
        //如果已点赞 die
        if($rees){
            die;
        }else{
            //将id time wzid插入guanxiwz表中
            $ress = DB::table('guanxiwz')->insert([
                ['uuuid'=>$id,'wztime'=>$time,'wzid'=>$wzid]
                ]);
            //获取点赞数
            $pass = $request->input('pass');
            //给点赞数加一
            $newpass = $pass+1;
            //修改点赞数
            $res = DB::table('article')->where('id',$wzid)->update(['pass'=>$newpass]);
            //判断是否执行成功
            if($res){
                echo $newpass;
            }else{
                echo 0;
            }
        }
    }
}
